<template>
    <view class="container text-df">
        <!-- <u-navbar :title="title" left-text="返回" right-text="帮助" ></u-navbar> -->
        <view class="cont">
            <scroll-view style="height: 100%;" :scroll-top="scrollTop" :scroll-y="true" class="scroll-Y" upper-threshold="200" 
                @scrolltoupper="getList" :scroll-with-animation="true">
                <view v-for="(item, index) in list" :key="index">
                    <!-- send=0 对方 -->
                    <view class="left" v-if="item.send == 0">
                        <view class="u-flex u-col-left">
                            <image class="header" :src="item.image || '../../static/icon/avatar.png'"></image>
                            <view class="text-left" v-if="item.type == 1">
                                {{ item.content }}
                            </view>
                            <view class="img-left" v-if="item.type == 2">
                                <image @click="previewImage(item.chat)" mode="widthFix" :src="item.chat"></image>
                            </view>
                            <view class="yuyin-box-left" @click="playVoice(item,index)" v-if="item.type == 3">
                                <image src="../../static/icon/yuyin.png" class="yuyin"></image>
                                <view class="yuyin-text">{{ item.voiceText }}</view>
                            </view>
                        </view>
                    </view>
                    <!-- send=1 自己 -->
                    <view class="right" v-if="item.send == 1">
                        <view class="u-flex u-col-left">
                            <view class="text-right" v-if="item.type == 1">
                                {{ item.content }}
                            </view>
                            <view class="img-right" v-if="item.type == 2">
                                <image @click="previewImage(item.chat)" mode="widthFix" :src="item.chat"></image>
                            </view>
                            <view class="yuyin-box-right" @click="playVoice(item,index)" v-if="item.type == 3" >
                                <view class="yuyin-text">{{ item.voiceText }}</view>
                                <image src="../../static/icon/yuyin.png" class="yuyin"></image>
                            </view>
                            <image class="header" :src="item.image || '../../static/icon/avatar.png'"></image>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        
        <view class="top">
            <view class="u-flex u-padding-20" >
                <u-search class="u-flex-1" placeholder="输入消息" searchIcon="" :showAction="false" v-model="content" v-if="xiaoxiFlg"></u-search>
            	<view class="btn1 u-flex-1" style="height: 64rpx;" @touchstart="startManager" @touchend="endManager" v-if="!xiaoxiFlg">{{xiaoxiTxt}}</view>
            	<view class="btn" @click="$noMultipleClicks(sendTxt)"  v-if="xiaoxiFlg">
            		发送
            	</view>
            </view>
            <view class="u-flex">
            	<view class="u-padding-top-10 u-padding-left-40" style="width: 142rpx;">
            	    <image @tap="chooseImage()" style="height: 102rpx;width: 102rpx;" src="../../static/image/upload.png"></image>
            	    <view class="photo">相册</view>
            	</view>
            	<view class="u-padding-top-10 u-padding-left-40" style="width: 142rpx;" v-if="voiceDisplay != 1">
            	    <image v-if="xiaoxiFlg" @tap="xianshi" style="height: 102rpx;width: 102rpx;" src="../../static/image/yuyin.png"></image>
                    <image v-if="!xiaoxiFlg" @touchstart="startManager" @touchend="endManager" style="height: 102rpx;width: 102rpx;" src="../../static/image/yuyin.png"></image>
            	    <view class="photo">语音</view>
            	</view>
            </view>
            <view style="height: constant(safe-area-inset-bottom); height: env(safe-area-inset-bottom);"></view>
        </view>
    </view>
</template>

<script>
    const recorderManager = uni.getRecorderManager();
    
    export default {
        data() {
            return {
                noClick:true,//连点
                title: '聊天详情',
                receive_id: '',
                content: '', //聊天内容
                unread_id: '', //未读消息 没有未读 为 0
                userInfo: '',
                timer: 0,
                
                id: '',
                pImg: '',
                tImg: '',
                status: 'loadmore', //是否显示没有更多了
                page: 1,
                list: [], 
                scrollTop: 0,
                old: {
                	scrollTop: 0
                },
                image: '',
                
                xiaoxiFlg: true,
                xiaoxiTxt:'长按开始录音',
                time: 0, //录音时间
                fn: '',
                voicePath: '',
                data: {},
                type: '',
                innerAudioContext: '',
                voiceDisplay: '',
            };
        },
        onHide() {
            uni.$emit('BACK_WECHAT')
        },
        onUnload() {
            uni.$emit('BACK_WECHAT')
        },
        onLoad(option) {
            // #ifdef APP-PLUS
            let _this = this
            var galleryPermission = plus.navigator.checkPermission("camera");
            if (galleryPermission == "undetermined") {
                // _this.$toast('用户获取相机功能，用于上传用户上传图片');
                _this.$toast('权限使用说明：相机用于拍照上传图片；录音用于录制语音消息。');
            }
            // #endif
            
            // #ifdef APP-PLUS
            recorderManager.start();
            var galleryPermission = plus.navigator.checkPermission("RECORD_AUDIO");
            if (galleryPermission == "undetermined") {
                this.$toast('录音权限使用说明：用于录制语音消息。');
            }
            // #endif
            
            recorderManager.onStop((res) => {
                if(this.time<1){
                    // this.$toast('语音时间过短'); 
            		this.xiaoxiTxt = '长按开始录音'
                    return; 
                } 
                this.voicePath = res.tempFilePath;
                this.$upLoadPic(this.voicePath).then((ret) => {
                    console.log(ret)
                    if (ret.success == 1000) {
            			this.xiaoxiFlg = true
            			this.xiaoxiTxt = '长按开始录音'
            			// this.$toast('语音发送成功');
                		this.sendMessage(3, '', ret.detail.image_id)
                    }
                });
            });
            
            if (option.data) {
                this.data = JSON.parse(option.data)
                console.log(this.data)
            }
            if (option.type) {
                this.type = option.type
                if (this.type == 1) {
                    // 从 客户列表 进入
                    uni.setNavigationBarTitle({
                    	title: this.data.resident_name
                    })
                } else if (this.type == 2) {
                    // 从 个人中心--项目报备列表 进入
                    uni.setNavigationBarTitle({
                    	title: this.data.broker_name
                    })
                } else if (this.type == 3) {
                    // 从 微聊列表 进入
                    uni.setNavigationBarTitle({
                    	title: this.data.user_name
                    })
                }
            } else {
                if (this.data.broker_name) {
                    // 从 我的经纪人或我的店长列表 进入
                    uni.setNavigationBarTitle({
                    	title: this.data.broker_name
                    })
                } else {
                    // 从 楼盘详情 进入
                    uni.setNavigationBarTitle({
                    	title: this.data.user_name
                    })
                }
            }
            this.getList()
            this.getVoiceDisplay()
            
            uni.$on('WECHAT', () => {
                this.page = 1;
                this.list = [];
                this.status = 'loadmore';
                this.getList();
            })
        },
        
        methods: {
             // 1隐藏
            getVoiceDisplay() {
            	this.$ajax('voice_display', {
                    
            	}).then(ret => {
            		if (ret.success == 1000) {
            			this.voiceDisplay = ret.detail.display
            		} else {
            			this.$toast(ret.msg);
            		}
            	});
            },
            
            
            playVoice(item,index) {
                console.log('播放录音',item);
                if (this.innerAudioContext != '') {
                    this.innerAudioContext.destroy()
                }
                this.innerAudioContext = uni.createInnerAudioContext();
                // this.innerAudioContext.src = item.chat;
                if (item.voiceText == '播放中...') {
                    this.innerAudioContext.stop();
                    this.innerAudioContext.onStop((res) => {
                        console.log('音频停止事件',res);
                        item.voiceText = '语音消息'
                    });
                } else {
                    this.innerAudioContext.src = item.chat;
                    item.voiceText = '播放中...'
                    this.innerAudioContext.play();
                    console.log('播放',item.id);
                    this.innerAudioContext.onEnded((res) => {
                        console.log('音频自然播放结束事件',res);
                        item.voiceText = '语音消息'
                    });
                    this.innerAudioContext.onStop((res) => {
                        console.log('音频停止事件',res);
                        item.voiceText = '语音消息'
                    });
                }
                
                this.innerAudioContext.onError((res) => {
                    console.log(res.errMsg);
                    console.log(res.errCode);
                });
            },
            
            // 开始录音
            startManager(e) {
                console.log(e);
                recorderManager.start();
            	this.time = 0
                this.fn = setInterval(() => {
                    this.time++;
                }, 1000);
            	this.xiaoxiTxt = '放开发送语音'
            },
            
            // 结束录音
            endManager(e) {
                console.log(e);
                recorderManager.stop();
            	this.xiaoxiTxt = '长按开始录音'
                clearInterval(this.fn);
            },
            
            //显示录音
            xianshi() {
                this.xiaoxiFlg = !this.xiaoxiFlg;
            },
            
            // 发送图片
            chooseImage() {
                uni.chooseImage({
                    success: res => {
                        // 设置url的值，显示控件
                        this.$upLoadPic(res.tempFilePaths[0]).then((ret) => {
                            console.log('发图', ret)
                            if (ret.success == 1000) {
                                this.image = ret.detail.image;
            					this.sendMessage(2, '', ret.detail.image_id)
                            }
                        });
                    }
                });
            },
            
            // 发送文字
            sendTxt(){
                if (!this.content) {
                    this.$toast('发送内容不能为空');
                    return
                }
            	this.sendMessage(1, this.content)
            },
            
            sendMessage(type, content, id) {
                console.log('发送', type, content, id)
                
                var cid = ''
                if (this.type == 1) {
                    // 经纪人 微聊 项目驻场
                    cid = this.data.resident_id
                } else if (this.type == 2) {
                    // 项目驻场等其他身份 微聊 经纪人
                    cid = this.data.broker_id
                } else if (this.type == 3) {
                    // 从微聊列表 进入
                    cid = this.data.receive_id
                } else {
                    // 从人员列表 或 楼盘详情 进入
                    cid = this.data.id
                }
                
                this.$ajax('send_message', {
                    user_token: this.$getSync('userToken'),
                    receive_id: cid,//接收人
                    type: type, //1文字 2图片 3语音
                    content: content, //文字内容
                    chat_id: id,//图片/语音id
                }).then(ret => {
                	if (ret.success == 1000) {
                        // var newData = ret.detail
                        // var oldData = this.list
                        // this.list = oldData.concat(newData)
                        this.list.push(ret.detail)
                        this.list.forEach(cur => {
                            if (!cur.voiceText) {
                                this.$set(cur, 'voiceText', '语音消息')
                            }
                        })
                        this.content = '';
                        setTimeout(() => {
                            var len = this.list.length; //遍历的数组的长度
                            this.scrollTop = 999999 * len; // 这里我们的单对话区域最高1000，取了最大值
                        	// this.scrollTop = 999999
                        },1000)
                        
                        console.log(this.scrollTop)
                	} else {
                		this.$toast(ret.msg);
                	}
                });
            },
            
            // 获取聊天详情列表
            getList() {
                var cid = ''
                if (this.type == 1) {
                    // 经纪人 微聊 项目驻场
                    cid = this.data.resident_id
                } else if (this.type == 2) {
                    // 项目驻场等其他身份 微聊 经纪人
                    cid = this.data.broker_id
                } else if (this.type == 3) {
                    // 从微聊列表 进入
                    cid = this.data.receive_id
                } else {
                    // 从人员列表 或 楼盘详情 进入
                    cid = this.data.id
                }
            	if (this.status == 'nomore') return;
            	this.status = 'loading';
            	this.$ajax('micro_chat', {
            		user_token: this.$getSync('userToken'),
            		page: this.page,
            		limit: 12,
                    receive_id: cid, //接受人id
            	}).then(ret => {
                    console.log(ret)
            		if (ret.success == 1000) {
                        var data = ret.detail.micro_chat
                        if (data && data.length > 0) {
                            // var newData = data.reverse();
                            var newData = data
                            var oldData = this.list;
                            this.list = newData.concat(oldData);
                            if (this.page == 1) {
                                setTimeout(() => {
                                    var len = data.length; //遍历的数组的长度
                                    // var len = ret.detail.count; //遍历的数组的长度
                                    this.scrollTop = 3000 * len; // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
                                    // this.scrollTop = 99999
                                },1000)
                            }
                            this.list.forEach(cur => {
                                this.$set(cur, 'voiceText', '语音消息')
                            })
                            // console.log(this.scrollTop)
                            this.page++;
                            this.status = 'loadmore'
                        } else {
                            this.status = 'nomore'
                        }
            		} else {
            			this.$toast(ret.msg);
            		}
            	});
            },
            
            previewImage(img){
            	var that = this
            	var image = []
            	image.push(img)
            	console.log(img)
            	 // 预览图片
            	uni.previewImage({
            		urls: image,
            		longPressActions: {
            			itemList: ['保存图片'],
            			success: function(data) {
            				uni.getImageInfo({
            					src: img,
            					success: function (src) {
            						uni.saveImageToPhotosAlbum({
            							filePath: src.path,
            							success: function () {
            								that.$toast('保存成功')
            							}
            						});
            					}
            				});
            			},
            			fail: function(err) {
            				console.log(err.errMsg);
            			}
            		}
            	});
            },
            
            scroll: function(e) {
            	// console.log(e)
            	this.old.scrollTop = e.detail.scrollTop
            },
            goTop: function(height) {
            	var that = this
            	this.scrollTop = this.old.scrollTop
            	this.$nextTick(() => {
                    var len = this.list.length; //遍历的数组的长度
                    // console.log(1500 * len)
                    this.scrollTop = 1500 * len; // 这里我们的单对话区域最高1000，取了最大值
                    // this.scrollTop = 999999
            	});
            },
        }
    };
</script>

<style lang="scss">
    
    .text-left{
        border-radius:0 20rpx 20rpx 20rpx;
        word-break: break-all;
        background-color: #fff;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
    }
    .img-left{
        border-radius:0 20rpx 20rpx 20rpx;
        word-break: break-all;
        background-color: #fff;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
    }
    .img-left>image{
        width: 300rpx;
    }
    
    .text-right{
        border-radius:20rpx 0 20rpx 20rpx;
        word-break: break-all;
        background-color: #a9e878;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
    }
    .img-right{
        border-radius:20rpx 0 20rpx 20rpx;
        word-break: break-all;
        background-color: #a9e878;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
    }
    .img-right>image{
        width: 300rpx;
    }
    
    
    .yuyin-box-left{
        border-radius:0 20rpx 20rpx 20rpx;
        width: 220rpx;
        text-align: left;
        padding: 20rpx;
        flex: 1;
        margin-left: 20rpx;
        background-color: #fff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    .yuyin-box-right{
        border-radius:20rpx 0 20rpx 20rpx;
        width: 220rpx;
        text-align: left;
        padding: 20rpx;
        flex: 1;
        margin-right: 20rpx;
        background-color: #fff;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
    .yuyin{
        width: 30rpx;
        height: 30rpx;
    }
    .yuyin-text{
        padding: 0 15rpx;
    }
    
    
    
    
    
    
    .bg-gr {
        background-color: #a9e878;
    }

    .user-img {
        width: 94rpx;
        height: 94rpx;
    }

    .container {
        display: flex;
        flex-direction: column;
        height: 100vh;
    }

    .cont {
        flex: 1;
        background: #f1f3fa;
        overflow: hidden;
    }

    .left .header,
    .right .header {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
    }

    .left {
        width: 100%;
        justify-content: flex-start;
        padding: 10px 20rpx;
        display: flex;
    }

    .right {
        width: 100%;
        justify-content: flex-end;
        padding: 10px 20rpx;
        display: flex;
    }

    .tip {
        background-color: #fd442f;
        border-radius: 50px;
        /* padding: 10rpx; */
        font-size: 22rpx;
        color: #fff;
        width: 40rpx;
        height: 40rpx;
        text-align: center;
        line-height: 40rpx;
    }

    .send {
        width: 56rpx;
        height: 56rpx;
    }

    .message {
        background: #f1f3fa;
        border-radius: 30rpx;
        padding: 26rpx;
        margin-right: 20rpx;
    }

    .photo {
        color: #aaaaaa;
        text-align: center;
        padding-top: 10rpx;
    }

    .top {
        background-color: #f6f6f6;
    }

    .search {
        background-color: #FFFFFF;
        height: 80rpx;
        line-height: 80rpx;
        padding-left: 30rpx;
    }
</style>
